#! /usr/bin/env perl

# use 5.010;
# use strict;       # debug off
# use warnings;     # debug off
use Encode::CN;
use PerlIO::encoding;
no warnings "all";  # debug on

my $sys = ("$^O" =~ /WIN/i ? 'windows' : 'linux');
my $rulefile_path = 'rules.rule';
my $encoding_in = ':encoding(utf8)';
my $encoding_console;
if ($sys eq 'windows') {
    $encoding_console = ':encoding(cp936)';
} else {
    $encoding_console = ':encoding(utf8)';
}

open my $rulefile, '<', $rulefile_path or die "open file '$rulefile_path' error: $!";
binmode $rulefile, $encoding_in;
binmode STDOUT, $encoding_console;
binmode STDIN, $encoding_console;

my @totalexp;
my @else;
my $welcome;

my $texts;
$texts .= $_ for(<$rulefile>);

close $rulefile;

sub loadrule
{
    {
        my @matched;
        @matched = $texts =~ /I:\s(.+)\n((?:.+\n)+)$/gm;
        while (@matched) {
            my $regex =  shift @matched;
            my $allanswer = shift @matched;
            chomp($allanswer);
            my @answers = split /\n/, $allanswer;
            my $ref = [$regex, \@answers];
            push @totalexp, $ref;
        }
    }
    {
        chomp(($welcome) = ($texts =~ /W:\n((?:.+\n)+)/gm));
    }    
    {
        chomp((my $elsetext) = ($texts =~ /E:\n((?:.+\n)+)/gm));
        @else = split /\n/, $elsetext;
    }
}

sub randlist
{
    @_[rand(@_)];
}

sub clean_screen {
    if ($sys eq 'windows') {
        system('cls');
    } else {
        system('clear');
    }
}

sub match
{
    my $user_input = shift;
    my @poss;
    for (@totalexp) {
        my $exp = $$_[0];
        my @answer = @{$$_[1]};
        
        if ($user_input =~ /.*(${exp}).*/ix) {
            push @poss, @answer;
        }
    }
    if (@poss == 0)
    {
        push @poss, @else;
    }
    @poss;
}

my $saytime = 0;

sub looping
{
    MAINLOOP: while ((print "$saytime)"), $_ = <STDIN>)
    {
        chomp;
        my @possible_list;
        next unless ($_);
        
        my $usr = $_;
        print 'Eliza> ';
        print &randlist(&match($usr)) . "\n";
        if ($saytime++ == 0) {
            &clean_screen();
            print $welcome . "\n";
        }
        #say @else[int(rand(scalar @else))];
    }
    return;
}


&loadrule();
&clean_screen();
&looping();
